<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomMessage from './components/RoomMessage.vue'
import RoomAction from './components/RoomAction.vue'
import io, { Socket } from 'socket.io-client'
import { onMounted, onUnmounted, ref, nextTick } from 'vue'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { DefaultEventsMap } from '@socket.io/component-emitter'
import type { TimeMessages, Message, ConsultOrderItem } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import { getConsultOrderDetail } from '@/services/consult'
import type { Image } from '@/types/consult'
import dayjs from 'dayjs'
import { showToast } from 'vant'
import { provide } from 'vue'
const route = useRoute()
const list = ref<Message[]>([])
const consult = ref<ConsultOrderItem>()
let socket: Socket<DefaultEventsMap, DefaultEventsMap>
// 页面加载完毕以后连接服务器
onUnmounted(() => {
  socket.close()
})

const getConsult = async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
}
onMounted(async () => {
  getConsult()
  // 建立链接，创建 socket.io 实例
  socket = io('https://consult-api.itheima.net/', {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  socket.on('connect', () => {
    // 建立连接成功
    console.log('connect')
  })

  socket.on('error', (event) => {
    // 错误异常消息
    console.log('error', event)
  })

  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('disconnect')
  })

  //判断到底是不是第一次加载 第一次就为true
  const initialMsg = ref(true)
  // 聊天记录 如果是第一次(默认消息)
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // 准备转换常规消息列表
    const arr: Message[] = []
    data.forEach((item, i) => {
      // 记录每一段消息中最的消息时间,获取聊天记录需要
      if (i === 0) time.value = item.createTime
      arr.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: item.createTime
      })
      arr.push(...item.items)
    })
    // 追加到聊天消息列表
    list.value.unshift(...arr)
    // 拿到聊天记录以后
    loading.value = false
    //没有聊天记录以后提示
    if (!arr.length) return showToast('没有更多聊天记录了')
    if (initialMsg.value) {
      //如果是第一次就要滚动到最底部 最新的消息
      nextTick(() => {
        //默认加载的消息，需要用最后一条消息设置已读，之前所有消息即是已读
        socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        window.scrollTo(0, document.body.scrollHeight)
        initialMsg.value = false
      })
    }
  })
  // 监听订单状态变化
  socket.on('statusChange', () => getConsult())
  // 接收消息
  socket.on('receiveChatMsg', async (event) => {
    list.value.push(event)
    await nextTick()
    //接收到消息的时候，需要把消息设置为已读
    socket.emit('updateMsgStatus', event.id)
    //滚动到第一条消息最底部
    window.scrollTo(0, document.body.scrollHeight)
  })
})

console.log(list)

const store = useUserStore()
const sendText = (text: string) => {
  // 发送信息需要  发送人  收消息人  消息类型  消息内容
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: { content: text }
  })
}

// 发送图片消息
const sendImage = (image: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: image }
  })
}

// 拉取聊天记录
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const loading = ref(false)
const onRefresh = () => {
  // 发送聊天记录事件 一页多少条数据 上一段聊天记录最早的时间 订单id
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}
const completeEva = (score: number) => {
  //找到未评价消息
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  // 然后去修改
  if (item) {
    // 获取评价评分
    item.msg.evaluateDoc = { score }
    //改成已评价状态
    item.msgType = MsgType.CardEva
  }
}
// 注入订单信息：提供医生ID和订单ID 跨组件通信
provide('consult', consult)
provide('completeEva', completeEva)
</script>
<template>
  <div class="room-page">
    <!-- 头部模块 -->
    <cp-nav-bar title="问诊室" />
    <!-- 状态栏组件 -->
    <RoomStatus :status="consult?.status" :conutdown="consult?.countdown" />

    <!-- 消息栏组件 -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <RoomMessage v-for="item in list" :key="item.id" :item="item" />
    </van-pull-refresh>
    <!-- 操作栏组件 根据订单状态只要不是问诊中就不能发消息发图片-->
    <RoomAction
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    />
  </div>
</template>
<style scoped lang="scss">
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
